package trainning.metro.controller;

import trainning.metro.domain.Card;
import trainning.metro.service.MetroService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;

public class MetroController {
    private Scanner sc = new Scanner(System.in);
    private MetroService ms = new MetroService();
    public void start() {
        while (true){
            System.out.println("--------欢迎来到合肥地铁一号线--------");
            System.out.print("请输入您的选择："+"   ");
            System.out.print("1.乘坐地铁"+"   ");
            System.out.print("2.办理地铁卡"+"   ");
            System.out.print("3.充值地铁卡"+"   ");
            System.out.println("4.退出系统");
            String choice = sc.next();
            switch (choice){
                case "1":
                    buyTicket();
                    break;
                case "2":
                    //办理地铁卡
                    registerCard();
                    break;
                case "3":
                    //充值地铁卡
                    recharge();
                    break;
                case "4":
                    System.exit(0);
                default:
                    System.out.println("您的输入有误，请重新输入");
                    break;
            }
        }
    }

    private void recharge() {
        System.out.println("请输入您的卡号");
        String cardId;
        while (true){
            cardId = sc.next();
            boolean flag = judgeId(cardId);
            //3.4判断卡号是否已存在
            int index = ms.isExist(cardId);
            if(index == -1){
                flag =false;
            }

            if(flag){
                break;
            }else {
                System.out.println("卡号不正确，请重新输入");
            }
        }

        //验证
        System.out.println("请输入您的姓");
        String x = sc.next();
        boolean flag = ms.verify(cardId,x);
        if(!flag){
            System.out.println("输入错误");
            return;
        }
        //输入正确，获取用户姓名
        String username = ms.getUsername(cardId);
        double money = ms.getMoney(cardId);
        System.out.println("您好，"+username+"您目前的金额为："+money);

        //充值
        double charge;
        loop:
        while (true) {
            System.out.println("请输入您需要充值的金额（最低30元）");
            charge = judgeMoney();
            if(charge < 30){
                System.out.println("充值金额过低，是否退出充值（Y/N）");
                String str = sc.next();
                switch (str){
                    case "Y":
                        return;
                    case "N":
                        continue;
                    default:
                        System.out.println("您的输入有误，请重新输入：");
                        break;
                }
            }else {
                break;
            }
        }

        //记录并输出
        money += charge;
        boolean flag2 = ms.charge(cardId,money);
        if(flag2){
            System.out.println("充值成功，目前"+username+"您的余额为"+money);
        }
    }

    private void registerCard() {
        //1.确认是否注册
        System.out.println("请确认是否注册：Y/N");
        loop1:
        while (true) {
            String input = sc.next();
            switch (input){
                case "Y":
                    //注册
                    break loop1;
                case "N":
                    //取消注册
                    System.out.println("您取消了注册");
                    return;
                default:
                    System.out.println("您的输入有误，请重新输入");
                    break;
            }
        }

        //2.输入姓名
        System.out.println("请输入您的姓名：");
        String username = sc.next();

        //3.输入卡号
        String cardId;
        System.out.println("请输入您的卡号（5位字符串，首字母必须是小写字母，后四位必须是数字）：");
        while (true) {
            cardId = sc.next();
            boolean flag = judgeId(cardId);
            //3.4判断卡号是否已存在
            int index = ms.isExist(cardId);
            if(index != -1){
               flag =false;
            }

            if(flag) {
                break;
            }else {
                System.out.println("卡号格式不正确，请重新输入");
            }

        }

        //4.充值
        System.out.println("请输入您需要充值的余额(最低30元)：");
        double money;
        while (true) {
            money = judgeMoney();
            if(money < 30){
                System.out.println("充值金额过低，请重新输入");
            }else {
                break;
            }
        }

        //5.创建卡号
        Card card = new Card(username,cardId,money);
        boolean flag = ms.addUser(card);
        if(flag){
            String un = ms.getUsername(cardId);
            System.out.println("注册成功，请保存好您的卡号信息：姓名"+un+"，卡号"+cardId+"，余额："+money);
        }
    }

    private double judgeMoney() {
        double money = 0.0;
        while (true) {
            try {
                //4.1输入金额
                String moneyStr = sc.next();
                money = Double.parseDouble(moneyStr);
            } catch (NumberFormatException e) {
                //若内容非法则重新输入
                System.out.println("输入非法内容，请输入正确金额：");
                continue;
            }
            break;
        }
        return money;
    }

    private boolean judgeId(String cardId){
        char [] chr = cardId.toCharArray();
        //3.1字符串长度为5
        if(chr.length != 5){
            return false;
        }
        //3.2首字母必须为小写字母
        if(chr[0] < 'a' || chr[0] > 'z'){
            return false;
        }
        //3.3后四位必须是数字
        for (int i = 1; i < chr.length; i++) {
            if(chr[i] < '0' || chr[i] > '9'){
                return false;
            }
        }
        return true;
    }

    private void buyTicket() {
        /*
        1.获得地铁站并打印
         */
        ArrayList<String> stations = ms.getStations();
        loop:
        while (true) {
            System.out.println("--------欢迎来到合肥地铁一号线--------");
            System.out.println("车站列表如下");
            System.out.println(stations);

        /*
        2.输入上车站和下车站
         */
            System.out.println("请输入您的上车站：");
            String startStation;
            while (true) {
                startStation = sc.next();
                boolean flag = judgeStation(startStation,stations);
                if(flag){
                    break;
                }else {
                    System.out.println("您输入的上车站不存在，请重新输入:");
                }
            }

            System.out.println("请输入您的下车站：");
            String endStation;
            while (true) {
                endStation = sc.next();
                boolean flag = judgeStation(endStation,stations);
                if(flag){
                    break;
                }else {
                    System.out.println("您输入的下车站不存在，请重新输入:");
                }
            }

        /*
        3.输入交通卡号
        若存在：记录并放行；
        不存在：提示是否注册；
         */
            loop1:
            while (true) {
                System.out.println("请输入您的交通卡号");
                String cardId = sc.next();
                int index = ms.isExist(cardId);
                if(index == -1){
                    while (true) {
                        System.out.print("卡号不存在，请选择："+"\t");
                        System.out.print("1.注册新用户"+"\t");
                        System.out.println("2.重新输入");
                        String str = sc.next();
                        switch (str){
                            case "1":
                                //注册新用户
                                registerCard();
                                break loop1;
                            case "2":
                                continue loop1;
                                //重新输入
                            default:
                                System.out.println("您的输入有误，请重新输入：");
                                break;
                        }
                    }
                }else {
                    SimpleDateFormat sdf = new SimpleDateFormat("<yyyy-MM-dd HH:mm:ss>");
                    long time = System.currentTimeMillis();
                    Date date = new Date(time);
                    String currentTime = sdf.format(date);

                    String log = currentTime+","+cardId+","+startStation+","+endStation;
                    ms.saveUserLog(log);
                    String username = ms.getUsername(cardId);
                    System.out.println(username+"购买成功！");
                    break loop;
                }
            }
        }
    }

    private boolean judgeStation(String station,ArrayList<String> stations){
        for (String s : stations) {
            if (s.equals(station)) {
                return true;
            }
        }
        return false;
    }
}
